package com.lambkit.module.cms.web.api.controller;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.lambkit.common.AjaxResult;
import com.lambkit.db.mgr.MgrTable;
import com.lambkit.db.sql.condition.ConditionBuilder;
import com.lambkit.db.sql.condition.SqlBuilder;
import com.lambkit.module.cms.rpc.model.CmsMenu;
import com.lambkit.module.cms.web.validator.CmsMenuValidator;
import com.lambkit.web.controller.LambkitController;

public class MenuApiController extends LambkitController {

	/**
	 * 单条数据
	 */
	public void index() {
		getTableView(CmsMenu.service().getTableName(), true);
		Long id = getParaToLong(0) == null ? getParaToLong("id") : getParaToLong(0);
		CmsMenu datas = CmsMenu.service().findById(id);
		renderJson(new AjaxResult(1, "success", datas));
	}
	
	@Before(CmsMenuValidator.class)
	public void save() {
		if(getRequest().getMethod().equals("POST")) {
			CmsMenu data = getModel(CmsMenu.class, "menu");
			boolean flag = data.save();
			if(flag) {
				renderJson(new AjaxResult(1, "success", data));
			} else {
				renderJson(new AjaxResult(0, "save", null));
			}
		} else {
			renderJson(new AjaxResult(0, "method", null));
		}
	}
	
	@Before(CmsMenuValidator.class)
	public void update() {
		if(getRequest().getMethod().equals("POST")) {
			CmsMenu data = getModel(CmsMenu.class, "menu");
			boolean flag = data.update();
			if(flag) {
				renderJson(new AjaxResult(1, "success", data));
			} else {
				renderJson(new AjaxResult(0, "update", null));
			}
		} else {
			renderJson(new AjaxResult(0, "method", null));
		}
	}
	
	public void delete() {
		if(getRequest().getMethod().equals("POST")) {
			Long id = getParaToLong(0) == null ? getParaToLong("id") : getParaToLong(0);
			CmsMenu data = CmsMenu.service().findById(id);
			if(data != null && data.delete()) {
				renderJson(new AjaxResult(1, "success", null));
			} else {
				renderJson(new AjaxResult(0, "delete", null));
			}
		} else {
			renderJson(new AjaxResult(0, "method", null));
		}
	}
	
	/**
	 * 分页
	 */
	public void page() {
		MgrTable tbc = getTableView(CmsMenu.service().getTableName(), true);
		if (tbc == null) {
			renderJson(new AjaxResult(0, "fail", "table config is null"));
			return;
		}
		ConditionBuilder cb = getConditionsSQL(tbc).build("");
		SqlBuilder sb = new SqlBuilder();
		String select = sb.appendSelect(tbc).build();
		sb.clear().appendFrom(tbc).appendConditions(cb);
		//排序
		String orderby = getPara("orderby");
		if(StrKit.notBlank(orderby)) sb.appendOrderBy(orderby);
		String sql = sb.build();
		Integer pNumber = getParaToInt("pageNum", 1);
		Integer pSize =  getParaToInt("numPerPage", 15);
		Page<CmsMenu> page = CmsMenu.service().dao().paginate(pNumber, pSize, select, sql, cb.getSqlParas());
		renderJson(new AjaxResult(1, "success", page));
	}
}
